<?php

namespace App\Services;

use App\Models\Crm_Member;
use App\Models\Crm_Member_Rotate;
use App\Models\Crm_User_Head;
use App\Traits\External;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

class SeasService
{
    public function getList($params)
    {
        $field = config('fields.listFields');
//        ResponseApi::printSql();
        $result = Crm_Member::getFilter($params)->select($field)
            ->Yesdrop()
            ->Nodel()
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $data = $result->toArray();
        $item = External::optionItem($data['data']);
        $list['list'] = $item;

        return $list;
    }

    public function seasDraw($params)
    {
        $ids = explode(',',$params['ids']);

        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Member::find($id);

                $res->isdrop = 'N';    //坠海状态
                $res->intotime = NULL;     //坠海时间
                $res->dropreason = NULL;   //坠海原因
                $res->dropremark = '';   //坠海备注
                $res->belongid = $params['uid'];     //变更归属人
                $res->droptime = Carbon::now()->addDay(15)->toDateTimeString();  //距离坠海时间
                $res->allottime = Carbon::now()->toDateTimeString();  //变更分配时间

                if(!$res->save()){
                    throw new \Exception("更新Crm_Member领取状态失败 $id");
                }
                $rotate = Crm_Member_Rotate::where('mid' , $id)->where('agencyid' , $params['aid'])->where('islast','Y')->first();
                if(!empty($rotate)){
                    $rotate->islast = 'N';
                    $rotate->save();
                    $olduserid = $rotate->olduserid;
                    $oldusername = $rotate->oldusername;
                }else{
                    $olduserid = NULL;
                    $oldusername = NULL;
                }

                $ret = Crm_Member_Rotate::create([
                    'agencyid' => $params['aid'],
                    'mid' => $id,
                    'explain' => '领取公海资源',
                    'remark' => $params['remark'],
                    'olduserid' => $olduserid,   //原归属人id
                    'oldusername' => $oldusername,  //原归属人名称
                    'islast' => 'Y',
                    'optionid' => $params['uid'],
                    'optionname' => $params['uname']
                ]);

                if(!$ret){
                    throw new \Exception("创建Crm_Member_Rotate流转记录失败 ID $id");
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function getHeadList($params)
    {
        $result = Crm_User_Head::getFilter($params)->first();
        return json_decode($result->params,true);
    }

    public function seasHeadUpdate($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_User_Head::getFilter($params)->first();
            $res->params = $params['params'];
            if(!$res->save()){
                throw new \Exception("更新公海列表表头失败" );
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }
}
